//
//  JDTypeCollectionView.swift
//  DragonWallet
//
//  Created by volantPig on 2025/9/14.
//

import UIKit

class JDTypeCollectionView: UIView {

    var gotoclassificationDetailCallBack:(()->())?
    
    var didChangeTypeCallBack:((JDGoodsTypeModel?)->())?
    
    var selectedIndex = 0
    
    var typeModels: [JDGoodsTypeModel?] = [JDGoodsTypeModel?]() {
        didSet {
            self.moveView.pageNumber =  Int(ceil(CGFloat(self.typeModels.count)/10.0))
        }
    }
    
    lazy var mainCollectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        
        let mainCollection = UICollectionView(frame: .zero, collectionViewLayout: layout)
        mainCollection.backgroundColor = .white
        mainCollection.delegate = self
        mainCollection.dataSource = self
        mainCollection.isPagingEnabled = true
        
        mainCollection.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "myCell")
        
        return mainCollection
    }()
    
    lazy var bottomView: UIView = {
        let bottom = UIView()
        bottom.backgroundColor = .white
        return bottom
    }()
    
    lazy var moveView: JDTypeLineView = {
        let move = JDTypeLineView()
        
        return move
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupUIElements()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUIElements() {
        self.addSubview(self.mainCollectionView)
        self.mainCollectionView.snp.makeConstraints { make in
            make.leading.trailing.top.equalTo(self)
            // 225 = 96+ 96 +33
            make.height.equalTo(90*2)
            make.bottom.equalTo(self).offset(-33)
        }
        
        
        self.addSubview(self.bottomView)
        self.bottomView.snp.makeConstraints { make in
            make.leading.trailing.equalTo(self)
            make.top.equalTo(self.mainCollectionView.snp.bottom)
            make.bottom.equalTo(self)
        }
        
        self.bottomView.addSubview(self.moveView)
        self.moveView.snp.makeConstraints { make in
            make.centerX.centerY.equalTo(self.bottomView)
            make.size.equalTo(CGSizeMake(33, 4))
        }
        
        
    }
    
}

extension JDTypeCollectionView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.typeModels.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath)
        
        for subV in cell.contentView.subviews {
            subV.removeFromSuperview()
        }
        
        let currentModel = self.typeModels[indexPath.row]
        
        let bgView = UIView()
        cell.contentView.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.leading.equalTo(cell.contentView).offset(0.5)//.offset(5)
            make.trailing.equalTo(cell.contentView).offset(-0.5)//.offset(-5)
            make.top.equalTo(cell.contentView).offset(8)
            make.bottom.equalTo(cell.contentView).offset(-0.5)
        }
        
        let typeImageV = UIImageView()
        bgView.addSubview(typeImageV)
        typeImageV.snp.makeConstraints { make in
            make.centerX.equalTo(bgView)
            make.top.equalTo(bgView).offset(4)
            make.size.equalTo(CGSizeMake(52, 52))
        }
        if currentModel?.name == "全部" || currentModel?.name == "分类"  {
            typeImageV.image = UIImage(named: currentModel?.logo ?? "")
        } else {
            typeImageV.downloadImage(currentModel?.logo ?? "")
        }
        
        let typeNameLabel = UILabel()
        bgView.addSubview(typeNameLabel)
        typeNameLabel.snp.makeConstraints { make in
            make.centerX.equalTo(bgView)
            make.top.equalTo(typeImageV.snp.bottom).offset(4)
            make.height.equalTo(18)
        }
        typeNameLabel.text = currentModel?.name//"休闲食品"
        
        
        if indexPath.row == self.selectedIndex {
            bgView.makeCorner(8)
            bgView.makeBorder(color("#FF5027"), 0.5)
            bgView.backgroundColor = color("#FF5027").withAlphaComponent(0.03)
            
            typeNameLabel.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 13, weight: .semibold), textColor: color("#FF5027"), numberOfLines: 1)
        } else {
            bgView.makeCorner(8)
            bgView.makeBorder(.white, 0.5)
            bgView.backgroundColor = .white
            
            typeNameLabel.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 13, weight: .regular), textColor: color("#FF5027"), numberOfLines: 1)
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSizeMake(floor((screenWidth-24.0)/5.0), 90)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 12)
//        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0.001
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0.001
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if self.selectedIndex == indexPath.row {
            return
        }

        let currentModel = self.typeModels[indexPath.row]
        
        if currentModel?.name == "分类" {
            print("点击了分类")
            self.gotoclassificationDetailCallBack?()
        } else {
            self.selectedIndex = indexPath.row
            self.mainCollectionView.reloadData()
            self.didChangeTypeCallBack?(currentModel)
        }
    }
    
}


class JDTypeLineView: UIView  {
    
    var lineWidth: CGFloat = 4
    
    var pageNumber: Int = 1 {
        didSet {
            // 更新 containerView 的宽度
            self.updateLine()
        }
    }
    
    lazy var containerView: UIView = {
        let container = UIView()
        container.backgroundColor = color("#F2EEEE")
        container.makeCorner(2.5)
        return container
    }()
    
    lazy var moveLine: UIView = {
        let line = UIView()
        line.backgroundColor = color("#FD5902")
        line.makeCorner(2.5)
        return line
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupUIElements()
    }
    
    func setupUIElements() {
        self.addSubview(self.containerView)
        self.containerView.snp.makeConstraints { make in
            make.centerX.centerY.equalTo(self)
            make.size.equalTo(CGSizeMake(33, 4))
        }
        
        self.moveLine.frame = CGRectMake(0, 0, 11, 4)
        self.containerView.addSubview(self.moveLine)
    }
    
    func moveLineAction(_ index: CGFloat = 0) {
        
        UIView.animate(withDuration: 0.2) {
            
            if index > CGFloat(self.pageNumber) {
                self.moveLine.frame = CGRectMake(CGFloat(self.pageNumber) * self.lineWidth, 0, self.lineWidth, 4)
            } else {
                self.moveLine.frame = CGRectMake(index * self.lineWidth, 0, self.lineWidth, 4)
            }
        }
        
    }
    
    func updateLine() {
        if self.pageNumber > 1 {
            self.lineWidth = 33.0/CGFloat(self.pageNumber)
            self.moveLine.frame = CGRectMake(0, 0, self.lineWidth, 4)
        } else {
            self.moveLine.frame = CGRectMake(0, 0, 33, 4)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
